package com.bdth.interceptor;

import com.bdth.annotation.Auth;
import com.bdth.controller.BaseController;
import com.bdth.utils.HtmlUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限拦截器
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	private final static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
	                         HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod method = (HandlerMethod) handler;
		String requestUrl = request.getRequestURI();
		if (requestUrl.contains("api")) {
			return super.preHandle(request, response, handler);
		}
		//System.out.println(requestUrl);
		Auth auth = method.getMethod().getAnnotation(Auth.class);
		////验证登陆超时问题  auth = null，默认验证
		if (auth == null || auth.verifyLogin()) {
			String baseUri = request.getContextPath();
			String path = request.getServletPath();
			//SysUser user = SessionUtils.getUser(request);

/*			if (user == null) {
				if (path.endsWith(".shtml")) {
					response.setStatus(response.SC_GATEWAY_TIMEOUT);
					response.sendRedirect(baseUri + "/login.html");
					return false;
				} else {
					response.setStatus(response.SC_GATEWAY_TIMEOUT);
					Map<String, Object> result = new HashMap<String, Object>();
					result.put(BaseController.SUCCESS, false);
					result.put(BaseController.LOGOUT_FLAG, true);//登录标记 true 退出
					result.put(BaseController.MSG, "登录超时.");
					HtmlUtil.writerJson(response, result);
					return false;
				}
			}*/
		}
		return super.preHandle(request, response, handler);
	}

}
